<?php
namespace App\Http\Controllers\Api\Buz;

use App\Http\Controllers\Controller;
use App\Lib\Code;
use App\Lib\SMSCode;
use App\Models\PlatUser;
use App\Services\ApiResponseService;
use App\Services\Lib\SMSServiceFactory;
use App\Services\SMSService;
use App\Validators\Buz\SMSValidator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SMSController extends Controller
{
    protected $smsInstance;

    public function __construct(SMSServiceFactory $SMSServiceFactory)
    {
        $this->smsInstance = $SMSServiceFactory->getSMSService(config('sms.driver'));
    }

    public function sendSms(Request $request,
                            SMSValidator $validator,
                            SMSService $SMSService)
    {
        $validator->with($request->all())->passesOrFail('send');
        $type = $request->input('type', 1);
        $content = SMSCode::getErrorMsg($type);
        $code = random_int(100000, 999999);
        switch ($type) {
            case SMSCode::REGISTER:
                $to = $request->input('to');
                if (PlatUser::where('phone', $to)->first()) {
                    return ApiResponseService::showError(Code::REGISTER_PHONE_EXISTS);
                    break;
                }
            case SMSCode::PWD_FORGOT:
            case SMSCode::PWD_RESET:
                $to = $request->input('to');
                $SMSService->setCacheCode($to, $code);
                $content = sprintf($content, $code);
                break;
            case SMSCode::REMIT:
            case SMSCode::VIEW_KEY:
            case SMSCode::MODIFY_REMIT:
            case SMSCode::MODIFY_TRADE:
            case SMSCode::MODIFY_LOGIN:
                $user = \JWTAuth::parseToken()->authenticate();
                $to = $user->phone;
                $SMSService->setCacheCode($to, $code);
                $content = sprintf($content, $code);
                break;
        }
        if (config('sms.debug')) {
            return response($SMSService->getCache($to));
        }
        if ($this->smsInstance->sendSMS($to, $content)) {
            return ApiResponseService::success(Code::SUCCESS);
        } else {
            return ApiResponseService::showError(Code::FATAL_ERROR);
        }
    }

}
